var SDKAPPID = 1400039219;
var PREFIX = 'zhuawawa_' + SDKAPPID;
var ACCOUNTTYPE = 14418;
var BIZID = 8525;
// 特别注意，这是本demo的业务接口地址，仅作为demo展示用。
// 您需要实现自己的业务后台接口，调用自己的业务域名及业务接口
var SVRDOMAIN = "https://sxb.qcloud.com/sxb_dev/";
var CATCHER_DOMAIN = "https://yun.tim.qq.com/v4/ilvb_doll_catch/";

var reportSto = null;
var AppInfo = {
  loginInfo : {
    identifier: null,
    token: null,
    userSig: null
  }
};

var query = {
  get: function (n) {
    var m = window.location.search.match(new RegExp("(\\?|&)" + n + "=([^&]*)(&|$)"));
    return !m ? "" : decodeURIComponent(m[2]);
  }
};
var Detector = {
  Android: function () {
    return /Android/i.test(navigator.userAgent);
  },
  iOS: function () {
    return /iPhone|iPad|iPod/i.test(navigator.userAgent);
  },
  safari: function () {
    return navigator.userAgent.toLowerCase().indexOf('safari/') > -1 && navigator.userAgent.toLowerCase().indexOf('chrome/') === -1;
  }
};
var AppSvr = {
  setErrorHandler: function (cb) {
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
      // Do something with response data
      // console.debug('axios',response);
      if (cb) {
        cb(response);
      }
      return response;
    }, function (error) {
      // Do something with response error
      return Promise.reject(error);
    });
  },
  login: function (opts, succ, err) {
    axios.post(SVRDOMAIN + '?svc=doll&cmd=fetchsig', JSON.stringify({
      "id": opts.username,
      "appid": SDKAPPID
    }))
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  },


  getRoomList: function (succ, err) {
    axios.get(SVRDOMAIN + '?svc=doll&cmd=roomlist')
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  },



  buildUrl: function (name ,domain) {
    var urlParams = {
      sdkappid: SDKAPPID,
      usersig: AppInfo.loginInfo.userSig,
      identifier: AppInfo.loginInfo.identifier,
      random: parseInt(Math.random(0, 1) * 100000000),
      contenttype: 'json'
    };
    var str = ""
    for (var key in urlParams) {
      if (str != "") {
        str += "&";
      }
      str += key + "=" + encodeURIComponent(urlParams[key]);
    }

    return (domain ? domain : CATCHER_DOMAIN) + name + "?" + str;
  },

  applyWsUrl: function (succ, err) {
    axios.post(this.buildUrl('room_addr'), JSON.stringify({
      "GroupId": parseInt(app.roomnum)
    }))
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  }
};


Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})


var renderUserListItv = null;
var remainTimeSto = null;
var app = new Vue({
  el: '#app-main',
  data: {
    form: {
      msg: null,
      username: null
    },
    logined: false,
    view: 1,
    roomList: [],
    roomnum:  null,
    roomInfo:null,
    loginInfo: null,
    joinRoomModal: false,
    createRoomModal: false,
    video_list: [],
    configRole: "user",
    websocket: null,
    catcher: {
      state: 0,
      waitNumber: 0,
      remain_time: 60,
      move: null
    },
    player: null,
    lvburl: null,
    nipple: null,
    alreadySendQueueRequest: 0,
    front: true,
    pressed: {
      start: false,
      left: false,
      up: false,
      right: false,
      down: false,
      catcher: false,
      togger: false,
      restart: false
    },

    Directive: {
      CTL_LEFT_START: "left",
      CTL_LEFT_END: "left_end",
      CTL_RIGHT_START: "right",
      CTL_RIGHT_END: "right_end",
      CTL_FORWARD_START: "up",
      CTL_FORWARD_END: "up_end",
      CTL_BACKWARD_START: "down",
      CTL_BACKWARD_END: "down_end",
      CTL_CATCH: "catch",
      CTL_STOP: "stop"
    },

    gameResult: 0, // -1 未中奖， 0 准备中，游戏中  1 中奖了
    playing: 0
  },
  components: {
    'vue-toastr': window.vueToastr
  },
  filters: {
    getSrcTinyId: function (val) {
      return val.split("_")[0]
    },
    getOpenId: function (val) {
      var videoId = val.split("_")[0]
      return WebRTCAPI.getOpenId(videoId);
    }
  },
  watch: {
    view(val) {
    }
  },

  computed: {
    showWin() {
      return this.gameResult === 1;
    },

    showLose() {
      return this.gameResult === -1;
    },

    remainTime() {
      return this.catcher.state == 1 && this.catcher.remain_time * 1 > 0 ? this.catcher.remain_time + "秒" : "";
    }
  },

  mounted() {
    var self = this
    AppSvr.setErrorHandler(function (response) {
      var data = response.data;
      var errorCode = typeof data.ErrorCode !== 'undefined' ? data.ErrorCode : data.errorCode
      switch (errorCode) {
        case 0:
        case 10003:
          break;
        case 10009:
          self.$root.$refs.toastr.w("登录态失效");
          self.logout();
          break;
        default:
          self.$root.$refs.toastr.w(data.errorInfo || data.ErrorInfo);
          break;
      }
    });

    var roomInfo = store.get(PREFIX + "roomInfo")
    if (roomInfo) {
      this.chooseRoom(roomInfo)
    }

    var self = this;
    var loginInfo = store.get(PREFIX + "loginInfo");
    if (loginInfo) {
      AppInfo.loginInfo = loginInfo;
      self.loginInfo = loginInfo;
      self.renderRoomList();
      return;
    } else {
      this.form = {
        username: "catcher-" + parseInt(Math.random(0, 1) * 1000000000000)
      };
      self.login();
    }
  },
  methods: {
    getOpenId: function (val) {
      var videoId = val.split("_")[0]
      return WebRTCAPI.getOpenId(videoId);
    },
    restoreVideo: function () {
      var self = this;
      setTimeout(function () {
        Array.prototype.forEach.call(self.video_list, function (item, idx) {
          var video = document.getElementById(item.videoId)
          if (!video) return
          if (item.stream && video && video.srcObject && video.srcObject.active === false) {
            video.srcObject = item.stream;
          }
        })
      }, 100);
    },
    login: function (e) {
      var self = this;
      if (this.form.username) {
        store.set(PREFIX + "username", this.form.username);
      }
      AppSvr.login(this.form, function (data) {
        if (data && data.errorCode === 0) {
          AppInfo.loginInfo.identifier = self.form.username;
          AppInfo.loginInfo.token = data.data.token;
          AppInfo.loginInfo.userSig = data.data.userSig;
          store.set(PREFIX + "loginInfo", AppInfo.loginInfo);
          self.loginInfo = AppInfo.loginInfo;
          self.$root.$refs.toastr.s("登录成功");
          //展示房间列表
          self.renderRoomList();
        } else {
          console.error(data)
          alert("获取UserSig失败, Info = " + JSON.stringify(data));
        }
      }, function (error) {
        console.error(error)
      });
    },

    logout: function () {
      store.remove(PREFIX + "loginInfo");
      this.view = 0;
    },

    renderRoomList: function () {
      var self = this
      AppSvr.getRoomList(function (data) {
        console.debug(data);
        self.roomList = data.data
      });
    },

    chooseRoom: function (roomInfo) {
      this.roomnum = roomInfo.id;
      this.roomInfo = roomInfo;
      // this.getLiveUrl();
      store.set(PREFIX + "roomnum", roomInfo.id)
      store.set(PREFIX + "roomInfo", roomInfo)
    },

    joinRoom: function () {
      var self = this;
      if (!this.roomnum) {
        this.$root.$refs.toastr.w('请先选择房间');
        return
      }
      //视频流初始化
      this.renderWatch();
      //操控逻辑初始化
      //初始化只是绑定函数，并不会有任何动作，
      //这里的时机可以放在开始游戏前
      this.initPlay();
    },

    initPlay: function() {
      //看这里看这里看这里
      // https://gitee.com/vqcloud/wawaji_H5
      var self = this
      TXWawaPlayer.init({
        OnWait: self.catcherHandlerWait,
        OnReady: self.catcherHandlerReady,
        OnState: self.catcherHandlerState,
        OnResult: self.catcherHandlerResult,
        OnTime: self.catcherHandlerTime,
        OnClose: function (info) {
          console.warn(info);
          if (info.code === TXWawaPlayer.ErrorCode.WebSocketClose.code) {
            self.$root.$refs.toastr.e(info.msg)
          }
        },
        OnError: function (error) {
          console.error(error);
          if (error.code === TXWawaPlayer.ErrorCode.WebSocketError.code) {
            self.$root.$refs.toastr.e(error.msg)
          }
        }
      })
    },
    catcherHandlerWait: function (data) {
      var self = this
      if (typeof data === 'undefined' || data < 0) {
        console.error('异常处理')
        return;
      }
      self.catcher.waitNumber = data;
      if (data > 0) {
        this.$root.$refs.toastr.s("排队中，请稍候");
        console.debug('排队中')
      } else if (data == 0) {
        console.debug('开始游戏')
      }
    },
    //准备好了，一定要在准备好以后，再开始游戏
    //开始游戏可以认为是一个投币的行为
    catcherHandlerReady: function (data) {
      TXWawaPlayer.startGame();
    },
    catcherHandlerResult: function (data) {
      var self = this
      console.debug('catcherHandlerResult', data)
      if (data === false) {
        this.gameResult = -1;
        //self.$root.$refs.toastr.w(`没有抽中，再接再厉`);
      } else {
        //self.$root.$refs.toastr.s(`抽中了！！！`);
        this.gameResult = 1;
      }
      this.alreadySendQueueRequest = 0
      this.catcher.state = 0
      setTimeout(function () {
        self.quitRoom();
      }, 2000)
    },
    catcherHandlerState: function (data) {
      //看这里看这里看这里
      // https://gitee.com/vqcloud/wawaji_H5
      // 等待中	TXWawaPlayer.MachineState.WAIT
      // 游戏中	TXWawaPlayer.MachineState.PLAY
      // 抓取中	TXWawaPlayer.MachineState.CATCH
      // 娃娃机的状态异常	TXWawaPlayer.MachineState.ERROR
      var self = this;
      self.catcher.state = data;
    },
    catcherHandlerTime: function (data) {
      this.catcher.remain_time = data
    },
    //切换摄像头
    toggleClass: function () {
      this.front = !this.front;
      $(".flex-item").toggleClass("sub-video main-video")
    },
    //移动
    catcherDoMove: function (dir) {
      TXWawaPlayer.controlClaw(dir)
    },
    initWebRTC: function () {
      var self = this;
      var rtclistener = {
        onRemoteCloseAudio: self.onRemoteCloseAudio,
        onRemoteLeave: self.onRemoteLeave,
        onRemoteCloseVideo: self.onRemoteCloseVideo,
        onKickout: self.onKickout,
        onInitResult: self.onInitResult,
        onLocalStreamAdd: self.onLocalStreamAdd,
        onRemoteStreamAdd: self.onRemoteStreamAdd,
        onWebSocketClose: self.onWebSocketClose,
        onRelayTimeout: self.onRelayTimeout,
        onIceConnectionClose: self.onIceConnectionClose,
        onRemoteStreamRemove: self.onRemoteStreamRemove,
        onUpdateRemoteStream: self.onUpdateRemoteStream,
        onChangeRemoteStreamState: function(){}
      };
      var loginInfo = {
        "token": AppInfo.loginInfo.token,
        "openid": AppInfo.loginInfo.identifier,
        "userSig": AppInfo.loginInfo.userSig,
        "sdkAppId": SDKAPPID,
        "accountType": ACCOUNTTYPE,
        "closeLocalMedia" : true
      };
      var ret = WebRTCAPI.init(rtclistener, loginInfo);
      if (ret !== 0) {
        alert("初始化失败！！！");
      }
    },
    // 获取RTMP直播url并渲染
    // 目前此 demo已经不使用 rtmp了
    // 如有需要可以参考
    getLiveUrl: function () {
      var param = [this.roomnum, this.roomInfo.front, "main"]
      console.debug( this.roomnum, this.roomInfo.front, "main" );
      var cryto = md5(param.join("_"))
      this.lvburl = window.location.protocol + `//${BIZID}.liveplay.myqcloud.com/live/${BIZID}_${cryto}.m3u8`
      if (this.player) {
        this.player.destroy()
        this.player = null
        this.$refs.lvb.innerHTML = ''
      }
      this.player = new TcPlayer('lvb', {
        "m3u8": this.lvburl,
        "autoplay": true,      //iOS下safari浏览器是不开放这个能力的
        "width": "100%",
        "height": "100vh",
        "wording": {
          2032: "请求视频失败，请检查网络",
          2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
        }
      });
    },

    //观看
    renderWatch: function () {
      this.view = 3;
      this.createRoomModal = false;
      this.joinRoomModal = false;
      this.initWebRTC();
    },

    //开始排队
    //这里应该向你的业务svr请求
    //业务svr进行权限判断/扣费逻辑完成后，返回ws地址
    //然后进行ws的排队
    startQueue: function () {
      var self = this
      if (this.alreadySendQueueRequest) return

      this.alreadySendQueueRequest = 1;
      AppSvr.applyWsUrl(function (data) {
        // 生成唯一的ID , 作为游戏id
        var playId = Date.now().toString(32) + Math.random().toString(32).split('.')[1];
        TXWawaPlayer.startQueue(playId, data.WsUrl);
      }, function (err) {
        console.error(err);
        self.alreadySendQueueRequest = 0;
        self.$root.$refs.toastr.e(JSON.stringify(err) )
        self.quitRoom();
      });
    },

    //退出房间
    quitRoom: function () {
      WebRTCAPI.quit()
      var self = this;
      this.view = 1;
      this.alreadySendQueueRequest = 0;
      this.video_list = [];
      TXWawaPlayer.quitGame();
      TXWawaPlayer.destroy();
    },
    //以下方法还是要有的，但是，不需要你做什么处理
    //当视频异常的时候，以下信息将有助于我们排查
    onLocalStreamAdd: function () { },
    onRemoteCloseAudio: function () {
      console.log("on remote close audio!");
    },
    onRemoteLeave: function () {
      console.log("on remote leave!");
    },
    onRemoteCloseVideo: function () {
      console.log("on remote close video!");
    },
    onIceConnectionClose: function () {
      console.log("onIceConnectionClose!");
    },
    onRelayTimeout: function () {
      console.error('relayTimeout')
    },
    //被T下线需要处理，同一账号只允许一处登录
    onKickout: function () {
      console.log("on kick out!");
      var self = this;
      self.$root.$refs.toastr.e("其他地方登录，被T下线");
      self.quitRoom();
      self.logout();
    },

    onJoinRoomCallback: function (result) {
      var self = this;
      if (result !== 0) {
        self.$root.$refs.toastr.e("create room failed!!!");
        return;
      }
    },

    onRemoteStreamAdd: function (stream, videoId, openId) {
      //每一个进入房间的观众，都会触发这个回调
      //但是没有开摄像头的用户是没有上行的，所以，判断stream是否存在
      //如果没有，直接return
      if( !stream ) return
      // 这里可以根据业务情况直接对srcObject进行绑定
      // 不一定要用这种方法处理
      var self = this;
      if (!_.find(this.video_list, function (o) {
        return o.videoId == videoId;
      })) {
        if (this.video_list.length == 0) {
          this.video_list.push({
            videoId: videoId,
            openId: openId,
            first: true,
            stream: stream
          });
        } else {
          this.video_list.push({
            videoId: videoId,
            openId: openId,
            stream: stream
          });
        }
      }
      // 为什么要这样做呢？
      // 因为这个时候页面这个时候还没更新完domtree
      if (!document.getElementById(videoId)) {
        setTimeout(function () {
          self.onRemoteStreamAdd(stream, videoId, openId);
        }, 50);
        return;
      }
      var video = document.getElementById(videoId);
      video.srcObject = stream;
    },
    onUpdateRemoteStream: function (stream, videoId, type, ssrState, openId) {
      this.onRemoteStreamAdd(stream, videoId, openId);
    },
    //视频流断开
    onRemoteStreamRemove: function (videoId) {
      var newArr = [];
      var needResetFirst = false;
      _.each(this.video_list, function (o) {
        if (o.videoId != videoId) {
          newArr.push(o);
        } else if (o.first) {
          needResetFirst = true;
        }
      });
      if (needResetFirst) {
        newArr[0].first = true;
      }
      console.debug('newArr', needResetFirst, newArr);
      this.video_list = newArr;
      this.restoreVideo();
      var openid = WebRTCAPI.getOpenId(videoId.split('_')[0])
    },
    // websocket 断开了，直接退房
    onWebSocketClose: function () {
      var self = this;
      self.quitRoom();
    },
    onInitResult: function (result) {
      var self = this;
      console.log("on init result : " + result);
      if (result !== 0) {
        var errorStr = "";
        if (result === -10001) {
          errorStr = "WebRTCJSAPI初始化参数不正确";
        } else if (result === -10002) {
          errorStr = "浏览器版本不正确";
        } else if (result === -10003) {
          errorStr = "sig校验失败";
        } else if (result === -10006) {
          errorStr = "WebSocket 初始化失败";
        } else {
          errorStr = "初始化错误";
        }
        alert(errorStr);
      } else {
        //初始化完成后，自动进入房间
        WebRTCAPI.createRoom({ roomid : self.roomnum, role : self.configRole}, function(result) {
          if (result !== 0) {
            sdkLog.error("create room failed!!!");
            return;
          }
          self.onJoinRoomCallback
        });
      }
    },
    //下抓
    catcherDoCatch: function(){
      TXWawaPlayer.controlClaw( this.Directive.CTL_CATCH );
    },
    //操控
    touch(dir) {
      if (!this.front) { // 摄像头反过来了，需要处理映射关系
        switch (dir) {
          case this.Directive.CTL_LEFT_START:
            dir = this.Directive.CTL_BACKWARD_START;
            break;
          case this.Directive.CTL_LEFT_END:
            dir = this.Directive.CTL_BACKWARD_END;
            break;
          case this.Directive.CTL_RIGHT_START:
            dir = this.Directive.CTL_FORWARD_START;
            break;
          case this.Directive.CTL_RIGHT_END:
            dir = this.Directive.CTL_FORWARD_END;
            break;
          case this.Directive.CTL_FORWARD_START:
            dir = this.Directive.CTL_LEFT_START;
            break;
          case this.Directive.CTL_FORWARD_END:
            dir = this.Directive.CTL_LEFT_END;
            break;
          case this.Directive.CTL_BACKWARD_START:
            dir = this.Directive.CTL_RIGHT_START;
            break;
          case this.Directive.CTL_BACKWARD_END:
            dir = this.Directive.CTL_RIGHT_END;
            break;
          case this.Directive.CTL_CATCH:
            dir = this.Directive.CTL_CATCH;
            break;
          case this.Directive.CTL_STOP:
            dir = this.Directive.CTL_STOP;
            break;
        }
      }
      TXWawaPlayer.controlClaw(dir);
    },
    hideResultPanel() {
      this.gameResult = 0;
    }
  }
})




